package muse.frames;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.BorderFactory;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;

import muse.Frame;
import muse.Launcher;
import muse.schedule.Task;
import muse.schedule.TaskData;
import muse.widgets.MuseWidget;
import muse.widgets.TextboxWidget;

public class Muse extends Frame implements ItemListener {
    private JPanel optionsPane;
    private TextboxWidget textPane;
    private MuseWidget musePane;
    private JComboBox jcb;
    private JComboBox sub;
    private boolean canSelect;
    private Task newTask;
    private State state;
    private enum State {
    	ROOT(new String[] {
			"Hey!\n\nFrom here you can do a number of things!\n\nSelect Goals to learn something new or if you want to set a goal for yourself.  You can even review and edit your existing ones!",
			"You can check the Calendar for scheduled Training Sessions!\n\nThese are essentially practices or study times that will help you improve at whatever it is you are trying to achieve or learn.  You gain exp and gold from completing them!  Review your accomplishments on the calendar, or even read and write in your journal!",
			"Select Motivation if you'd like me to try and inspire you!  I can offer inspirational quotes and videos.\n\nYou'd be surprised as to what a small pep talk can do!",
			"Finally, with EXP & Gold, you can review your Level!\n\nWhat does that mean?  Well, it means you can review how much you've learned, gained, and grown in any of the goals and skills you've worked on!  I'll even tell you how much gold you have!"
    	}, new String[] {"Goals", "Calendar", "Motivation", "Exp"}, null),
    	GOALS(new String[] {
			"Are you going to set a new goal to learn, or do you wish to review your existing ones?"
    	}, new String[] {"New", "Existing", "Back"}, ROOT),
    	NEW(new String[] {
    			
    	}, new String[] {"Search", "Preset", "Create", "Back"}, GOALS),
    	PRESET(new String[] {
    			
    	}, new String[] {"Select", "Search", "Back"}, GOALS),
    	SELECT(new String[] {
    			
    	}, new String[] {"Review", "Modify", "Accept", "Back"}, PRESET),
    	REVIEW(new String[] {
    			
    	}, new String[] {"Resources", "Classes", "Schedule", "Back"}, SELECT),
    	ACCEPT(new String[] {
    		"Alright, you are making a commitment to learn!"
    	}, new String[] {"Back"}, ROOT),
    	MODIFY(new String[] {
    			
    	}, new String[] {"Back"}, SELECT),
    	RENAME(new String[] {
    			
    	}, new String[] {"Back"}, MODIFY),
    	CHANGED(new String[] {
    			"Changes have been saved.  Great work!"
    	}, new String[] {"Back"}, MODIFY);
    	private String[] text;
    	private String[] choices;
    	private State parent;
    	State(String[] textBox, String[] choices, State parent) {
    		text = textBox;
    		this.choices = choices;
    		this.parent = parent;
    	}
    	public State getParent() {
    		return parent;
    	}
    	public String[] getText() {
    		return text;
    	}
    	public String[] getChoices() {
    		return choices;
    	}
    }
    public Muse()
    {
    	canSelect = false;
    	sub = new JComboBox();
    	sub.addItemListener(new ItemListener() {
    		public void itemStateChanged(ItemEvent ie) {
    			if(ie.getStateChange() == ItemEvent.SELECTED && !canSelect) {
    				if(sub.getSelectedIndex() == 0)
    					return;
    				canSelect = true;
    				int index = sub.getSelectedIndex();
    				sub.removeAllItems();
    				sub.addItem("");
    				for(int i = 0; i < Task.getIdCap(); i++)
    					if(Integer.parseInt(Task.getTask(i).getData("category")) + 1 == index)
    						sub.addItem(Task.getTask(i).getData("name"));
    			}
    		}
    	});    	
    	
        this.setLayout(new BorderLayout());
        JPanel all = new JPanel();
        JPanel top = new JPanel();
        JPanel bot = new JPanel();

        all.setLayout(new GridLayout(2,1,5,5)); //2 rows, 1 col, xpad, ypad
        all.add(top);
        all.add(bot);

        jcb = new JComboBox();
        jcb.setSelectedItem(null);

        optionsPane = new JPanel();
        optionsPane.add(jcb);
        optionsPane.setBorder(BorderFactory.createLineBorder(Color.green));

        musePane = new MuseWidget();
        musePane.setBorder(BorderFactory.createLineBorder(Color.blue));

        textPane = new TextboxWidget();
        textPane.setPreferredSize(new Dimension(320,220));

        top.setLayout(new GridLayout(1,2,5,5));
        top.add(musePane);
        top.add(optionsPane);

        bot.setBorder(BorderFactory.createLineBorder(Color.black));
        bot.add(textPane);

        bot.setBorder(BorderFactory.createLineBorder(Color.red));
        this.add(all);
        setState(State.ROOT);
    }
    
    public void init() {
    	super.init();
    	newTask = null;
    	setState(State.ROOT);
    }

	@Override
	public void itemStateChanged(ItemEvent arg0) {
		if(arg0.getStateChange() == arg0.SELECTED) {
			String selected = (String)((JComboBox)arg0.getSource()).getSelectedItem();
			if(selected.isEmpty())
				return;
			if(selected.equals("Back")) {
				setState(state.getParent());
				return;
			} 
			state = State.valueOf(selected.toUpperCase());
			if(selected.equals("Calendar") || selected.equals("Schedule")) {
				Launcher.getWindow().changeScreen(MFrame.JOURNAL);
			} else if(selected.equals("Select")) {
				if(!canSelect || ((String)sub.getSelectedItem()).isEmpty())
					return;
				else {
					setState(State.SELECT);
					Task parent = null;
					TaskData td = TaskData.getData().get(sub.getSelectedItem()).cloneMe();
					for(int i = 0; i < Task.getIdCap(); i++)
						if(Task.getTask(i).getData("name").equals(td.getName())) {
							parent = Task.getTask(i);
							break;
						}
					newTask = new Task(td, parent);
					textPane.removeAllFromPanel();
					textPane.addToPanel(new Modify());
				}
			} else if(selected.equals("Accept")) {
				Task.addTask(newTask);
				setState(State.ACCEPT);
			} else if(selected.equals("New")) {
				int count = 0;
				for(int i = 0; i < Task.getIdCap(); i++)
					if(Task.getTask(i) != null && Task.getTask(i).isEnabled())
						count++;
				if(count >= 5)
					textPane.setMessage(new String[] {"Unfortunately, we cannot set any more goals.  Any more than 5 and you may run the risk of overworking yourself.  Don't forget the saying, 'don't spread yourself too thin!'"});
				else setState(state);
			} else {
				setState(state);
			}
			switch(state) {
			case PRESET:
				sub.removeAllItems();
				sub.addItem("");
				sub.setPreferredSize(new Dimension(200, 40));
				for(String s : Task.categories)
					sub.addItem(s);
				textPane.addToPanel(sub);
				break;
			default: textPane.removeFromPanel(sub);
			}
		}
	}
	private void setState(State state) {
		this.state = state;
		jcb.removeItemListener(this);
		jcb.removeAllItems();
		System.out.println(jcb.getItemCount());
		jcb.addItem("");
		for(String s : state.getChoices())
			jcb.addItem(s);
		textPane.setMessage(state.getText());
		jcb.addItemListener(this);
		textPane.removeAllFromPanel();
		if(state == State.MODIFY)
			textPane.add(new Modify());
	}
	private class Modify extends JPanel {
		private JButton confirm;
		private Modify modify;
		
		public Modify() {
			setPreferredSize(new Dimension(textPane.getWidth(), 200));
			modify = this;
	    	confirm = new JButton("Confirm");
	    	confirm.addActionListener(new ActionListener() {
	    		public void actionPerformed(ActionEvent e) {
	    			setState(State.MODIFY);
	    		}
	    	});
	    	add(new Root());
		}
		public void paintComponent(Graphics g) {}
		private class Root extends JPanel implements ActionListener{
			public Root() {
				setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
				add(new JLabel("<html><u><b>" + newTask.getData("name") + "</b></u></html>"));
				add(new JButton("Rename"));
				add(new JButton("Schedule"));
				add(new JButton("Set Overall Weight"));
				add(new JButton("Set Deadline"));
				for(Component c : getComponents())
					if(c instanceof JButton)
						((JButton) c).addActionListener(this);
			}
			public void actionPerformed(ActionEvent e) {
				if(e.getActionCommand().equals("Rename")) {
					modify.add(new Rename());
					modify.remove(this);
				} else if(e.getActionCommand().equals("Schedule")) {
					
				} else if(e.getActionCommand().equals("Set Overall Weight")) {
					modify.remove(this);
					modify.add(new Weighter());
				}
				validate();
			}
			public void paintComponent(Graphics g) {}
		}
		private class Weighter extends JPanel implements ActionListener {
			public Weighter() {
				setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
				JTextArea jt = new JTextArea() {
					public void paintComponent(Graphics g) {}
				};
				jt.setBackground(null);
				jt.setText("You can set the overall weight of you goal.  Consider it the difficulty of the goal you're trying to achieve - essentially how hard of a challenge it is to you.");
				jt.setWrapStyleWord(true);
				jt.setLineWrap(true);
				add(new JButton("EASY"));
				add(new JButton("CHALLENGING"));
				add(new JButton("HARD"));
				for(Component c : getComponents())
					if(c instanceof JButton)
						((JButton) c).addActionListener(this);
			}
			public void actionPerformed(ActionEvent e) {
				int w;
				if(e.getActionCommand().equals("EASY")) {
					w = 0;
				} else if(e.getActionCommand().equals("CHALLENGING")) {
					w = 1;
				} else if(e.getActionCommand().equals("HARD")) {
					w = 1;
				}
				setState(State.CHANGED);
			}
			public void paintComponent(Graphics g) {}
		}
		private class Rename extends JPanel {
			public Rename() {
				textPane.setMessage(new String[] {"What do you wish to rename this Goal/Skill to? Remember that it will still display as \"Improving your grades\" to your friends and on your MUSE community profile."});
				setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
				add(Box.createRigidArea(new Dimension(200, 40)));
				final JTextArea jt2 = new JTextArea("Enter Name");
				jt2.setEditable(true);
				jt2.setPreferredSize(new Dimension(200,40));
				add(jt2);
				JButton jb1 = new JButton("Confirm");
				jb1.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						if(!jt2.getText().isEmpty() && !jt2.getText().equals("Enter Name")) {
							newTask.setParam("name", jt2.getText());
							setState(State.CHANGED);
							validate();
						}
					}
				});
				add(jb1);
			}
			public void paintComponent(Graphics g) {}
		}
	}
}